#!/usr/bin/env python3


import sys
import re

def update_markdown_headers(file_path):
    # Read the Markdown file
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.readlines()
    except FileNotFoundError:
        print(f"File {file_path} not found")
        return

    except Exception as e:
        print(f"Error reading file: {e}")
        return

    # Track header numbering for up to 6 levels
    counters = [0] * 6
    new_content = []
    in_code_block = False  # Flag to track code block state
    # Match headers: # followed by space and optional number, then content
    header_pattern = re.compile(r'^(#+)\s+(?:(?:\d+\.)*\d+\s+)?([^\s].*)$')

    for line in content:
        # Check for code block start/end
        if line.strip().startswith('```'):
            in_code_block = not in_code_block
            new_content.append(line)
            continue

        # Skip processing inside code blocks
        if in_code_block:
            new_content.append(line)
            continue

        # Try to match a header
        match = header_pattern.match(line)
        if match:
            level = len(match.group(1)) - 1  # Header level (# -> 0, ## -> 1, ...)

            # Update counter for current level
            counters[level] += 1
            # Reset counters for lower levels
            for i in range(level + 1, len(counters)):
                counters[i] = 0

            # Generate numbering (e.g., 1.2.3)
            number = '.'.join(str(counters[i]) for i in range(level + 1) if counters[i] > 0)

            # Use the header text, stripping any existing number
            header_text = match.group(2).strip()
            # Construct new header line
            new_line = f"{match.group(1)} {number} {header_text}\n"
            new_content.append(new_line)
        else:
            new_content.append(line)

    # Write back to file
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(new_content)
        print(f"Updated index in {file_path}")
    except Exception as e:
        print(f"Error writing file: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: mkindex <markdown_file>")
        sys.exit(1)

    file_path = sys.argv[1]
    update_markdown_headers(file_path)
